package blog.db;

import java.util.Vector;

import blog.ConstString;
import blog.util.StringUtils;

public class ShortCutDB {
	private static StorageConnectWithIndex store;
	private static String errorString;
	
	public static boolean openDB()
	{
		if ( store==null )
		{
			try {
				Class myclass;
				myclass = new ShortCut( ).getClass();
				store = StorageConnectWithIndex.open(ConstString.DB_NAME_SHORT_CUT, true, myclass);
				store.setSortField(ShortCut.FIELD_VISIT_COUNT, StorageConnectWithIndex.SORT_TYPE_DESC);
			} catch (Exception e) {
				errorString = StringUtils.combin(ConstString.DB_ERR_COMMON_OPEN_FAILED, e.getMessage());
			}
		}
		return store==null;
	}
	
	public static void closeDB()
	{
		if ( store!=null )
		{
			store.close();
			store = null;
		}
	}
	
	public static String getLastError()
	{
		return errorString;
	}
	
	public static boolean add( ShortCut shortcut )
	{
		if ( store!=null )
		{
			try {
				store.add(shortcut);
				return true;
			} catch (Exception e) {
				errorString = ConstString.DB_ERR_COMMON_OPERATION_FAILED;
			}
		}
		return false;
	}
	
	public static boolean udpate( ShortCut shortcut )
	{
		if ( store!=null )
		{
			try {
				store.update(shortcut);
				return true;
			} catch (Exception e) {
				errorString = ConstString.DB_ERR_COMMON_OPERATION_FAILED;
			}
		}
		return false;
	}
	
	public static boolean delete( ShortCut shortcut )
	{
		try {
			store.delete(shortcut);
			return true;
		} catch (Exception e1) {
			errorString = ConstString.DB_ERR_COMMON_OPERATION_FAILED;
		}
		return false;
	}
	
	public static ShortCut[] getAllIndex()
	{
		Vector result =  store.getAllIndex();
		ShortCut[] returnObj = new ShortCut[result.size()];
		result.copyInto(returnObj);
		return returnObj;
	}
}